<script lang="ts" setup>
import { ref, reactive, computed, watch, onMounted } from 'vue';
import API from '@/services';
import { Message } from '@arco-design/web-vue';
import { IconInfoCircle, IconDown } from '@arco-design/web-vue/es/icon';
import { store } from '@/store';

const emit = defineEmits(['updateItem']);
const {
  board: { putAuthorizeById },
  userInfoService: { getUser, getUserRoles }
} = API;
const authorizeVisible = ref(false);
const authorizeForm = reactive({
  id: 0, // 看板id
  authorizeRole: [],
  authorizeUser: []
});
const props = withDefaults(
  defineProps<{
    title: string;
  }>(),
  {
    title: ''
  }
);
const authorizeFormRef = ref();
const authorizeRoleList = computed(
  () => store.state.indextree.authorizeRoleList
);
const authorizeUserList = computed(
  () => store.state.indextree.authorizeUserList
);

// 获取角色
const getAuthorizeRoleList = async () => {
  try {
    const { code, data }: any = await getUserRoles({});
    if (code === 200) {
      store.commit('indextree/changeAuthorizeRoleList', data);
    }
  } catch (error) {
    console.log(error);
  }
};

// 获取用户
const getAuthorizeUserList = async () => {
  try {
    const { code, data }: any = await getUser({});
    if (code === 200) {
      store.commit('indextree/changeAuthorizeUserList', data);
    }
  } catch (error) {
    console.log(error);
  }
};

// 请求用户角色数据
const getAuthorizeList = () => {
  if (!authorizeRoleList.value || !authorizeRoleList.value.length) {
    getAuthorizeRoleList();
  }
  if (!authorizeUserList.value || !authorizeUserList.value.length) {
    getAuthorizeUserList();
  }
};

// 显示弹窗
const showAuthorizeModal = (item: any) => {
  authorizeForm.id = item.id;
  authorizeForm.authorizeRole = item?.authorize?.roleCodes || [];
  authorizeForm.authorizeUser = item?.authorize?.userCodes || [];
  setTimeout(() => {
    authorizeVisible.value = true;
  }, 500);
};

// 关闭弹窗之前
const onBeforeOk = async (done: any) => {
  const err = await authorizeFormRef.value.validate();
  if (!err) {
    done(true);
  } else {
    done(false);
  }
};
// 点击确定
const authorizeFetch = async () => {
  try {
    let res = await putAuthorizeById(
      { id: authorizeForm.id },
      {
        roleCodes: authorizeForm.authorizeRole,
        userCodes: authorizeForm.authorizeUser
      }
    );
    return res;
  } catch (error) {
    throw error;
  }
};
const handleOk = () => {
  authorizeFetch()
    .then((res: any) => {
      if (res.code === 200) {
        Message.success('授权成功');
        authorizeVisible.value = false;
        emit('updateItem');
        resetForm();
      } else {
        Message.error(res.msg);
      }
    })
    .catch(() => {
      // Message.error('授权失败');
    });
};

// 点击取消
const handleCancel = () => {
  authorizeVisible.value = false;
  authorizeFormRef.value.resetFields();
  authorizeFormRef.value.clearValidate();
};

// 重置表单
const resetForm = () => {
  authorizeForm.authorizeRole = [];
  authorizeForm.authorizeUser = [];
};

defineExpose({ showAuthorizeModal });
</script>

<template>
  <a-modal
    v-model:visible="authorizeVisible"
    :on-before-ok="onBeforeOk"
    @ok="handleOk"
    @cancel="handleCancel"
    @open="getAuthorizeList"
    unmountOnClose
    width="36%"
    modal-class="auth-modal"
  >
    <template #title>
      <span style="font-weight: bold"> {{ props.title }}</span>
    </template>
    <div>
      <div class="tips">
        <icon-info-circle :style="{ fontSize: '16px', color: '#3c6eff' }" />
        <span
          >被授权的用户或角色将拥有对当前看板进行编辑、发布、授权和删除的操作权限；</span
        >
      </div>
      <a-form
        :model="authorizeForm"
        ref="authorizeFormRef"
        class="authorize-form"
      >
        <a-form-item field="authorizeRole" label="授权角色" show-colon>
          <a-select
            v-model="authorizeForm.authorizeRole"
            placeholder="请选择"
            multiple
            :style="{ minHeight: '36px' }"
          >
            <template #arrow-icon>
              <IconDown class="arco-select-arrow-icon" />
            </template>
            <a-option
              v-for="item of authorizeRoleList"
              :value="item.value"
              :label="item.label"
              :key="item.value"
            />
          </a-select>
        </a-form-item>
        <a-form-item field="authorizeUser" label="授权用户" show-colon>
          <a-select
            v-model="authorizeForm.authorizeUser"
            placeholder="请选择"
            multiple
            :style="{ minHeight: '36px' }"
          >
            <template #arrow-icon>
              <IconDown class="arco-select-arrow-icon" />
            </template>
            <a-option
              v-for="item of authorizeUserList"
              :value="item.value"
              :label="item.label"
              :key="item.value"
            />
          </a-select>
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<style lang="scss" scoped>
::v-deep(.arco-form-item-label-col) {
  width: 16%;
  text-align: right;
  flex: 0 0 16%;
}
::v-deep(.arco-form-item-wrapper-col) {
  flex: 0 0 84%;
  width: 84%;
}
.tips {
  background: #ebf0fe;
  border: 1px solid rgba(57, 110, 254, 1);
  border-radius: 3px;
  padding: 8px 12px;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 18px;
  > img {
    width: 20px;
    height: 20px;
  }
  > span {
    font-size: 12px;
    color: #33353b;
    line-height: 20px;
    padding-left: 10px;
  }
}
.authorize-form {
  padding-bottom: 330px;
}
</style>

<style lang="scss">
.auth-modal {
  .arco-modal-body {
    padding: 18px;
    .arco-select-view-multiple .arco-select-view-tag {
      background-color: #f6f8fc;
      font-size: 12px;
      color: #33353b;
      padding: 2px 9px;
      border-radius: 4px;
    }
  }
}
</style>
